﻿using System;
using System.ComponentModel;
using System.Threading;

namespace Utils
{
	[Serializable]
    public class PropertyChangedNotifier : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged Members

		[field: NonSerialized]
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

		// Used to decouple the calling thread from the operations done by the receiver of the event
		protected virtual void OnPropertyChangedAsync(string propertyName)
		{
			if (this.PropertyChanged != null)
			{
				if (!ThreadPool.QueueUserWorkItem(state => this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName))))
				{
					throw new InvalidOperationException("The event couldn't be queued on the thread pool");
				}
			}
		}

        #endregion
    }
}
